#!/usr/bin/env python
#coding=utf-8

import urllib, types, time, platform, socket, json, urllib2
from flask.ext.sqlalchemy import Pagination
from flask import request, current_app, session
from codingabc.helpers import toint
from decimal import Decimal
from codingabc.helpers import log_debug, log_info, log_error
from codingabc.database import db
from app.models.menu import Menu
from app.models.role import RoleMenu
from app.services.wx.message_send import SendTemplateMsg
from xpinyin import Pinyin


def getip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
     s.connect(('www.baidu.com', 0))
     ip = s.getsockname()[0]
    except:
     ip = "127.0.0.1"
    finally:
     s.close()
    return ip


def model_to_dict(model):
    """ orm model转换成dict """

    ret = {}
    for c in model.__table__.columns:
        ret[c.name] = getattr(model, c.name)

    return ret

def model_to_dict_only(model, only=[]):
    """ orm model转换成dict - only版 """

    __dict = model_to_dict(model)

    _dict = {}
    for key in only:
        _dict[key] = __dict.get(key, None)

    return _dict

def ml_to_dl(model_list):
    """ model list to dict list """

    return [model_to_dict(m) for m in model_list]

def kt_to_dict(kt):
    """ KeyedTuple转换成Dict """

    return kt._asdict()

def ktl_to_dl(kt_list):
    """ KeyedTuple List转换成Dict List """

    return [kt_to_dict(kt) for kt in kt_list]

def urlencode(params):
    """ url转码 """

    if not params:
        return ''

    _params = params.copy()
    for k,v in params.items():
        if isinstance(v, types.StringType) or isinstance(v, types.UnicodeType):
            _params[k] = v.encode('utf8')

    return urllib.urlencode(_params)


def object_name(id, Object, name):
    """获取对象名称"""

    if id <= 0:
        return u''

    object_info = Object.query.get_or_404(id)
    if not object_info:
        return u''

    object_name = object_info.category_name
    return getattr(object_info,name,'')


def list_pagination(query_list, page=1,page_size=20):
    pagination  = Pagination(None, page, page_size, len(query_list), None)
    if page and page_size and len(query_list) > 0:
        a = (page -1)*page_size; b = ((page - 1)*page_size + page_size)if page > 1 else page_size
        query_list = query_list[a:b]

    return [query_list,pagination]


def easy_query_filter(Object,q,query_dict={}):
    """查询"""

    if not Object:
        log_info(u'请传入查询对象。')
        return q

    if not q:
        log_info(u'请传入q。')
        return q

    query_name_list = query_dict.keys()
    for query_name in query_name_list:
        attr = query_dict.get(query_name)
        if isinstance(attr, int) == True:
            if attr >= 0:
                q = q.filter(getattr(Object, query_name) == attr)
                continue
            continue
        if attr:
            attr = attr.strip()
            if query_name[-4:] == 'time':
                if query_name[:5] == 'begin':
                    begin_time = time.mktime(time.strptime(attr,'%Y-%m-%d'))
                    q = q.filter(getattr(Object, query_name[6:]) >= begin_time)
                    continue

                if query_name[:3] == 'end':
                    end_time = time.mktime(time.strptime(attr,'%Y-%m-%d')) + 24*3600
                    q = q.filter(getattr(Object, query_name[4:]) < end_time)
                    continue
                q = q.filter(getattr(Object, query_name).like(u'%'+attr+u'%'))
                continue
            q = q.filter(getattr(Object,query_name).like(u'%'+attr+u'%'))
            continue
    return q


def get_params(param_dict):
    """ 获取参数 """

    param_list = {}
    for key, value in param_dict.iteritems():
        request_param = request.form if request.method == 'POST' else request.args
        if value is int:
            param = toint(request_param.get(key, '0'))
            param = param if param > 0 or request_param.get(key, '') == '0'  else -1
            param_list[key] = param
            continue
        if value is str:
            param = request_param.get(key, '').strip()
            if key[-4:] == 'time':
                try:
                    param = int(time.mktime(time.strptime(param,'%Y-%m-%d %H:%M')))
                except Exception, e:
                    pass
            param_list[key] = param
            continue

        if value == Decimal:
            param = Decimal(request_param.get(key,'0.0'))
            param_list[key] = param
            continue

        if value is None:
            param = request.files[key]
            param = param if param else ''
            param_list[key] = param
            continue

    return param_list


def img_first(img_list=[]):
    """获取图片列表的第一张图片"""

    img_list = img_list.split(',')

    if len(img_list) > 0:
        return img_list[0]

    return ''

def img_list(img_list=[]):
    """图片列表"""

    img_list = img_list.split(',')

    if len(img_list) > 0:
        return img_list

    return ''


def menu(role_id=0):
    """菜单"""
    _menu_list = []

    if role_id > 0:
        # 获取用户权限列表
        rm_list = RoleMenu.query.filter(RoleMenu.role_id == role_id).all()
        rm_id_list  = [rm.menu_id for rm in rm_list]

        menu_list = Menu.query.filter(Menu.parent_id == 0).\
                            filter(Menu.menu_id.in_(rm_id_list)).\
                            order_by(Menu.sort_order.desc()).all()

        # 如果是超级管理员，就显示所有菜单
        if role_id == 1:
            menu_list = Menu.query.filter(Menu.parent_id == 0).\
                            order_by(Menu.sort_order.desc()).all()

        for _menu in menu_list:
            # # 如果找不到端点就continue掉
            # if not _menu.endpoint:
            #     continue

            menu_child_list = Menu.get_child_list(_menu.menu_id)
            child_list = []
            for child in menu_child_list:
                # 如果找不到端点就continue掉
                if not child.endpoint:
                    continue

                # 如果menu_id没有在获取用户权限id列表就continue掉
                if role_id != 1 and child.menu_id not in rm_id_list:
                    continue

                child_dict = {}
                child_dict['menu_id'] = child.menu_id
                child_dict['name'] = u'%s'% child.endpoint_name
                child_dict['endpoint'] = child.endpoint
                child_list.append(child_dict)

            base_menu_dict ={
                        'menu_id':_menu.menu_id,
                        'name':u'%s'% _menu.endpoint_name,
                        'endpoint':u'%s'% _menu.endpoint,
                        'icon':u'%s' % _menu.endpoint_icon,
                        'child':child_list
                    }
            _menu_list.append(base_menu_dict)
    return _menu_list


def child_menu_list(id=0):
    """子菜单列表"""

    if id <= 0:
        return u'参数出错'

    menu_list = db.session.query(Menu.menu_id, Menu.endpoint_name).\
                    filter(Menu.parent_id > 0).\
                    filter(Menu.parent_id == id).all()

    return menu_list


def print_list_split(print_list, split_num=0):
    """打印列表切割"""

    if split_num == 0:
        print_list = print_list[0:3]
    else:
        start = split_num*3
        end = split_num*3 + 3
        print_list = print_list[start:end]

    return print_list


def parent_menu_name(menu_id=0):
    """获取上级菜单名称"""

    if menu_id <= 0:
        return u''

    menu =  Menu.query.get(menu_id)

    if not menu:
        return u''

    parent_menu = Menu.query.get(menu.parent_id)

    if not parent_menu:
        return u''

    parent_menu_name = parent_menu.endpoint_name

    if session.get('parent_menu_name') == parent_menu_name:
        return u''

    session['parent_menu_name'] = parent_menu_name
    return parent_menu_name


def get_word_pinyin(word):
    """获取汉字拼音"""

    if not word:
        return ''

    py = Pinyin()
    pinyin =  py.get_pinyin(u'%s'%word, ' ')
    log_info('### pinyin:%s'% pinyin)

    return pinyin


def wx_send_msg(MsgJson=None):
    """微信推送"""
    accessToken = session.get('accessToken')
    appId       = current_app.config['WEIXIN_APPID']
    appSecret   = current_app.config['WEIXIN_SECRET']
    current_time = int(time.time())
    left_time   = session.get('left_time') if session.get('left_time') else 0

    send_temp_msg = SendTemplateMsg()
    if left_time - current_time <= 10:
        accessToken = send_temp_msg.get_access_token()
        session['accessToken'] = accessToken

    industry_info  = send_temp_msg.get_industry(accessToken)
    if industry_info.get('errcode') > 0:
        if industry_info.get('errcode') in (40001, 42001):
          session['errcode'] = industry_info.get('errcode')
          postUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'%(appId, appSecret)
          res     = urllib2.urlopen(postUrl).read()
          accessToken_info = json.loads(res)
          accessToken = accessToken_info['access_token']
          session['accessToken'] = accessToken
        else:
          set_industry = send_temp_msg.api_set_industry(1,29, accessToken)
          industry_info  = send_temp_msg.get_industry(accessToken)

    send_temp_msg.send(MsgJson, accessToken)


def request_url_str():

    request_url     = request.url
    url_root        = request.url_root
    request_url_str = request_url.replace(url_root,'')
    request_url_str = '/' + request_url_str

    return request_url_str


def record_page(page, sum_page=0):
    """记录访问页面的页数"""
    if page >= 1:
        session['page'] = page
    page = session.get('page', 1)

    if sum_page <= 0:
        return page

    if sum_page < page:
        page = 1

    return page


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False


def make_cache_key(*args, **kwargs):
    """缓存带动态参数的视图函数"""

    path = request.path
    args = str(hash(frozenset(request.args.items())))
    return (path + args).encode('utf-8')
